<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html class="win-frame">
<head>
<title>用户管理-新建用户</title>
<%@include file="/common/head.jsp" %>
<link href="<%=request.getContextPath()%>/static/plugin/zTree/css/zTreeStyle/zTreeStyle.css" rel="stylesheet">
<link href="<%=request.getContextPath()%>/static/styles/css/org.css" rel="stylesheet">
<script src="<%=request.getContextPath()%>/static/plugin/zTree/js/jquery.ztree.all-3.5.min.js"></script>
<script src="<%=request.getContextPath()%>/static/js/org.js"></script>
<style type="text/css">
 .tree-title {
    border-bottom: 2px solid #fb9337;
    color: #666;
    font-size: 13px;
    font-weight: 600;
    margin: 0 15px 15px 0;
    padding: 0 40px 5px 5px;
    background-color: #ffffff;
 }
</style>
</head>
<body class="iframe-page">
<div class="page-title-wrapper">
    <div class="page-title">
        <div class="page-title-text">
            <span>用户管理</span>
            <span class="split"></span>
            <span>新建用户</span>
        </div>
        <a id="goBack" class="btn-return distance-left" href="javascript:;"><i class="icon icon-arrow-left"></i>返回上级</a>
    </div>
    <div class="page-title-border"></div>
</div>

<form id="userForm" method="post">
  <div id="left" style="width:80%;float:left">
	 <div class="form-wrapper">
		<div class="h4 distance-double">
	        <span class="h4-title"><i class="icon icon-setting"></i>基本信息</span>
	        <span class="h4-border"></span>
	    </div>
     
	    <div class="form-cont">
	        <p class="form-cont-title"><span class="field-required">*</span>登录名</p>
	        <input type="text" id="username" name="username" class="summer-input" /> 
	     </div>
	     
	    <div class="form-cont">
	        <p class="form-cont-title"><span class="field-required">*</span>姓名</p>
	        <input type="text" id="realname" name="realname" class="summer-input summer-validatebox" data-validatebox="validType:['required','maxLength[40]']"/>
	     </div>
	     
	    <div class="form-cont">
	        <p class="form-cont-title"><span class="field-required">*</span>所属机构</p>
	        <input type="text" id="orgName" name="org" readonly="readonly"  class="summer-input summer-validatebox distance-right" data-validatebox="tipPosition:'bottom',validType:['required']"/>
	     </div>
	     
	    <div class="form-cont">
	        <p class="form-cont-title">角色分配</p>
	        <input type="text" id="role" class="summer-input distance-right" readonly="readonly"/>
            <input type="hidden" id="roleIds" name="roleIds"/>
            <input type="button" class="btn btn-ok" id="showRole" value="点击查看"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title"><span class="field-required">*</span>人员类型</p>
	        <input type="text" id="type" name="type" class="summer-input summer-validatebox" data-validatebox="validType:['required']"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title"><span class="field-required">*</span>用户状态</p>
	        <input type="text" id="isUsable" name="isUsable" class="summer-input summer-validatebox" data-validatebox="validType:['required']"/>
	     </div>
	     
		 <div class="form-wrapper">
		 <div class="h4 distance-double">
	        <span class="h4-title"><i class="icon icon-setting"></i>详细信息</span>
	        <span class="h4-border"></span>
	     </div> 
      
	    <div class="form-cont">
	        <p class="form-cont-title">性别</p>
	        <input type="text" id="gender" name="gender" class="summer-input"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">电话</p>
	       <input type="text" id="tel" name="tel" class="summer-input summer-validatebox" data-validatebox="validType:['phone']"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">手机</p>
	        <input type="text" id="mobile" name="mobile" class="summer-input summer-validatebox" data-validatebox="validType:['mobile']"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">邮箱</p>
	        <input type="text" id="email" name="email" class="summer-input summer-validatebox" data-validatebox="validType:['email']"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">职位</p>
	         <input type="text" id="position" name="position" class="summer-input summer-validatebox" data-validatebox="validType:['maxLength[40]']"/>
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">排序号</p>
	        <input type="text" id="orderNo" name="orderNo" class="summer-input summer-validatebox" data-validatebox="validType:['betweenInteger[1,100000]']"/>
	     </div>
	</div>
	
	 <div class="form-btn-wrapper" id="funcbar">
        <a class="btn btn-normal" id="backBtn">关闭</a>
    </div>
  </div>
  </div>
	
  <div id="right" style="width:20%;float:right;">
      <div id="roleDiv" style="display: none">
          <p class="tree-title">角色树</p>
          <ul id="roleTree" class="ztree"></ul>
      </div>
   </div>	
</form>
<script>
    var roleZtree,
        orgCode = '${param.org}', //用户管理页面选中的组织机构树
        permission = CommonUtil.getPermission('user');
    
    $(function () {
    	//初始化funcbar
    	 $('#funcbar').prepend($.funcbar({
             type: 'button',
             data: permission,
             permit: ['user:add', 'user:addc']
         }));
    	
    	
    	//组织机构树
    	$('#orgName').org({
    		 'selectedMulti': false,
   	         'event': 'keyup',
   	         'url': USER_CONST_URL.ORG_TREE,
   	         'idKey': 'code',
   	         'pIdKey': 'pCode',
   	         'rootId': orgCode,
   	         'height': 450,
   	         'width': 600
    	}); 
    	//初始化人员类型
    	initCombobox('type', COMMON_URL.getCode + '?type=T_DM_USER_TYPE', '0');
    	//初始化用户状态
    	initCombobox('isUsable', COMMON_URL.getCode + '?type=T_DM_USER_ISUSABLE', '1');
    	//初始化性别
    	initCombobox('gender', COMMON_URL.getCode + '?type=T_DM_USER_GENDER');
    	
    	 //在用户管理页面选中组织机构树，新建页面显示树并默认选中值
    	if (orgCode) {
    		$('#orgName').org('setValues',orgCode);
    	}
    	
    	//点击显示/隐藏角色树
    	$('#showRole').on('click', showRole);
    	
    	//保存按钮
    	$('#funcbar').on('click', 'a[data-permit="user:add"]', {isContinue: false},  submit);
    	//保存并添加按钮
    	$('#funcbar').on('click', 'a[data-permit="user:addc"]', {isContinue: true},  submit);
    	
    	//返回按钮
    	$('#backBtn,#goBack').on('click',backMain);
    	
    	//校验登录名是否可用
        validateExist('#username','username', USER_CONST_URL.CHECKEXIST, ['required','betweenLength[4,16]','username','regexp'], "名称可用");
    });
    
    
    //初始化combobox
    function initCombobox(id, url, defaultValue, async, menuHeight) {
        $('#' + id).combobox({
            valueField: 'code',
            textField: 'name',
            async: async? async: false,
            url: url,
            menuHeight: menuHeight? menuHeight: 'auto',
            defaultValue: defaultValue ? defaultValue : '' 
        });
    }
    
    //显示角色树
    function showRole() {
        if (!roleZtree) {
            initTree('roleTree', USER_CONST_URL.ROLE_TREE, 'id', 'parentId', true, clickRole, true);
        }
        $('#roleDiv').show();
    }
    
    //点击角色树给角色分配赋值
    function clickRole(event, treeId, treeNode) {
    	if (event.type == 'click') {
           roleZtree.checkNode(treeNode, !treeNode.checked,true);
    	} else {
    	  roleZtree.checkNode(treeNode, treeNode.checked,true);
    	}
    	var nodes = roleZtree.getCheckedNodes(true),
    	    nodeName = [],
    	    nodeIds = [];
    	$.each(nodes, function(index, node){
            nodeName.push(node.name);
            nodeIds.push(node.id);
        });
        $('#roleIds').val(nodeIds.join());
        $('#role').val(nodeName.join());
    }
    
    //初始化树
    function initTree(id, url, idKey, pIdKey, checkEnable, click, async) {
    	var setting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: idKey,
                    pIdKey: pIdKey
                }
            },
            check: {
                enable: checkEnable,
                chkStyle: "checkbox",
                chkboxType : { "Y" : "ps", "N" : "ps" }
            },
            callback: {
                onClick: click,
                onCheck: click
            }
        };
    	
    	$.ajax({
             url: url,
             async: async,
             dataType: 'json',
             success: function (data) {
            	 roleZtree = $.fn.zTree.init($('#' + id),setting,data.data); 
                 expandNode(idKey, pIdKey);
             }
             
        });
    }
    
    // 展开树节点
    function expandNode(idKey, pIdKey) {
       var nodeId = '${param.expandId}',
           ztree = roleZtree,
           node;
       
       if (nodeId) {
           // 获取需要自动展开的节点
           node = ztree.getNodeByParam(idKey, nodeId, null);
       } else {
           // nodeId为空,展开根节点
           node = ztree.getNodeByParam(pIdKey, null, null);
       }
       // 如果该节点不包含子节点,则展开其父节点
       if (node && !node.isParent) {
          node = node.getParentNode(); 
       }
       ztree.expandNode(node, true, false, true);
    }
    
    
    //表单提交
    function submit(event) {
         $("#userForm").form({
        	 buttons : ['#saveBtn','#saveBtnContinue'],
             ajax: {
                 url: USER_CONST_URL.ADD
             },
             onSubmitSuccess: function (data) {
            	 $.stip({
  	                type:'ok',//显示类型 有info、 ok、 danger
  	                text: '保存成功！',
  	                onBeforeHide: function () {
  	            	  var isContinue = event.data.isContinue;
                   	  if (isContinue) {
                          resetForm();
                   	  } else {
                   		  backMain();
                   	  }
  	               }
              	});
              }
         }).form("submit");
    }
    
    //保存并继续清空form
    function resetForm(){
        $('#username,#realname,#role,#roleIds,#email,#tel,#mobile,#orderNo,#position').val('');
        $('#type').combobox('setValue', '0');
        $('#isUsable').combobox("setValue", '1');
        $('#gender').combobox('clear');
        //取消选择的组织机构树
        var selectOrgNode = $('#orgName-hidden').val();
        if (selectOrgNode.length) { 
        	//用户点击新建时选择组织机构树
        	if (orgCode) {
        		//保存选择的和新建的不一样
        		if (selectOrgNode != orgCode) {
        			//取消新选择的code
        			$('#orgName').org('setValues', '');
        			//选中默认选的并赋值显示机构树
        			$('#orgName').org('setValues',orgCode);
                }
        	} else {
        		$('#orgName').org('setValues', '');
        	}
        }
        
        //取消所有角色树
        if (roleZtree) {
        	 roleZtree.checkAllNodes(false);
             var roleNodes = roleZtree.getSelectedNodes();
             $.each(roleNodes, function(index, node) {
                 roleZtree.cancelSelectedNode(node);
             });
        }
    }
    
    //返回主页面
    function backMain() {
    	window.location.href = USER_CONST_URL.INIT_MAIN;
    }
    
    //校验用户名是否可用
    function validateExist(id, name, url, validType, message) {
        $(id).validatebox({
            rules: {
                regexp: {
                    validator: function (value,param) {
                        var result = false,
                            params = {}, 
                            key = name;
                            params[key] = value;
                            
                        $.ajax({
                            type: 'post',
                            url: url,
                            data: params,
                            dataType: 'json',
                            async: false,
                            success: function (data) {
                            	result = !(data.result == 'exist');
                            }
                        });
                        return result;
                    },
                    message: message
                }
            },
            validType: validType
        });
    }
    
    //请求url
    var USER_CONST_URL = {
    	INIT_MAIN: basePath + '/sys/user/init',
       	ADD: basePath + "/sys/user/add",
       	ORG_TREE: basePath + '/sys/inner/getOrgTree',
       	ROLE_TREE: basePath + '/sys/inner/getRoleTree',
       	CHECKEXIST: basePath + '/sys/user/checkUsernameExist'
    };
    
</script>
</body>
</html>